package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Employee;
import com.itheima.reggie.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;

/**
 * 员工管理模块
 */
@Slf4j
@RestController //@Controller + @ResponseBody
@RequestMapping("employee")
@Api(tags = "员工模块")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    //员工登录
    @PostMapping("login")
    @ApiOperation("员工登录")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session) {
        String username = employee.getUsername();
        String password = employee.getPassword();

        // 1. 先根据用户名查询
        Employee e = employeeService.lambdaQuery()
                .eq(Employee::getUsername, username)
                .one();
        if (e == null) {
            //说明账号不存在
            return R.error("账号不存在");
        }
        // 2. 判断密码是否一致
        if (!StringUtils.equals(e.getPassword(), DigestUtils.md5DigestAsHex(password.getBytes()))) {
            //说明密码错误
            return R.error("密码错误");
        }
        // 3. 判断用户状态
        if (e.getStatus() == 0) {
            //说明账号已被禁用
            return R.error("账号已被禁用");
        }
        //4. 说明登录成功，一定要将用户存入session中
        session.setAttribute("employee", e.getId());
        return R.success(e);
    }


    //员工退出
    @PostMapping("logout")
    public R<String> logout(HttpSession session) {
        //1. 删除session中的用户信息，销毁session对象
        //session.removeAttribute("employee");
        session.invalidate();
        //2. 返回成功标识 code=1
        return R.success("退出成功");
    }


    //添加员工
    @PostMapping
    public R<String> save(@RequestBody Employee employee, HttpSession session) {
        //1. 补全员工信息（密码，时间，创建人）
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes(StandardCharsets.UTF_8)));
        //2. 添加操作，直接调用service
        employeeService.save(employee);
        return R.success("添加成功");
    }


    //分页查询
    @GetMapping("page")
    public R<Page<Employee>> page(Integer page, Integer pageSize, String name) {
        //1. 创建一个分页对象Page
        Page<Employee> pageInfo = new Page<>(page, pageSize);

        //2. 分页查询 select * from employee where name like ? order by update_time limit ?, ?
        employeeService.lambdaQuery()
                .like(StringUtils.isNotBlank(name), Employee::getName, name) //过滤条件
                .orderByDesc(Employee::getUpdateTime)   //排序条件
                .page(pageInfo); //分页查询

        //3. 响应数据
        return R.success(pageInfo);
    }


    //启用、禁用员工状态
    @PutMapping
    public R<String> update(@RequestBody Employee employee, HttpSession session) {
        //update employee set status=?, update_time=?, update_user=?  where id=?
        //补全员工信息（修改时间，修改人）
        //调用业务层修改数据库
        log.info("当前线程ID：{}", Thread.currentThread().getId());
        employeeService.updateById(employee); //employee对象中属性为空的会自动忽略
        return R.success("修改成功");
    }

    //根据id查询员工信息
    @GetMapping("{id}")
    public R<Employee> findById(@PathVariable Long id) {
        //调用业务层查询数据库  select * from employee where id=?
        Employee employee = employeeService.getById(id);
        return R.success(employee);
    }
}




